
package com.mybatis.generator.core;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * @author 
 * @date 2015年12月19日 下午7:36:02
 */
public class FreemarkerUtils {

	private static Configuration cfg = new Configuration();

	public static File getTemplate(String name) throws Exception {
		if (name == null || "".equals(name)) {
			throw new Exception("参数异常");
		}
		PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();

		Resource resource = patternResolver
				.getResource("classpath:ftl/");
		
		return resource.getFile();
		
//		InputStreamReader read = new InputStreamReader(
//				resource.getInputStream(), "UTF-8");
//		BufferedReader bufferedReader = new BufferedReader(read);
//
//		StringBuilder sb = new StringBuilder();
//		String lineTxt = null;
//		while ((lineTxt = bufferedReader.readLine()) != null) {
//			sb.append(lineTxt);
//		}
//
//		bufferedReader.close();
//		read.close();

//		return sb.toString();

	}

	public static String process(String templateName, Table table)
			throws Exception {
		cfg.setDefaultEncoding("UTF-8");
		FileTemplateLoader templateLoader = new FileTemplateLoader(getTemplate(templateName));
//		StringTemplateLoader stringLoader = new StringTemplateLoader();
//		stringLoader.putTemplate(templateName, getTemplate(templateName));
		cfg.setTemplateLoader(templateLoader);
		Template temp = cfg.getTemplate(templateName + ".ftl", "utf-8");
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		temp.process(table, new OutputStreamWriter(bos));
		return bos.toString("UTF-8");
	}

	
	public static void write(String path, String content) throws Exception {
		File generatorFile = new File(path);
		if (generatorFile.isDirectory()) {
			throw new Exception(path + "不是一个文件");
		}
		File parentFile = generatorFile.getParentFile();
		if (!parentFile.exists() && !parentFile.mkdirs()) {
			throw new Exception("文件夹创建失败");
		}
		if (generatorFile.exists()) {
			//System.out.println("文件：" + generatorFile.getPath() + "已存在！");
			return;
		}
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(generatorFile), "UTF-8"));
		bw.write(content);
		bw.close();
		System.out.println("save:" + path);
	}

}
